'''
Created on Oct 5, 2012

@author: Himanshu
'''
import copy
import numpy as np

class LOOCV():
    """
    Object to perform LOOCV 
    """
    def __init__(self):
        self.featureSet = []
        self.targetVector = []
        
    def setFeatureSet(self,featureSet):
        self.featureSet = featureSet
        
    def setTargetVector(self,targetVector):
        self.targetVector = targetVector
        
    def experiment(self,classifier):
        """
        main method to perform LOOCV experiment. Returns the computed class for each instance in self.featureSet
        """
        if (self.featureSet.__len__() == 0):
            print "Set the feature set first!"
            return
        if (self.targetVector.__len__() == 0):
            print "Set the target vector first!"
            return
        computedClass = []        
        for i in range(0,self.featureSet.__len__()):
            print " ----- Running LOOCV Experiment " , i+1 , " --------"
            reducedFeatureSet = copy.deepcopy(self.featureSet)
            reducedFeatureSet.pop(i)
            reducedTargetVector = copy.deepcopy(self.targetVector)
            reducedTargetVector.pop(i)
            classifier.setTrainingSet(reducedFeatureSet)
            classifier.setTargetVector(reducedTargetVector)
            computedClass.append(classifier.classify(self.featureSet[i]))
        return computedClass      
            
    def countErrors(self,computedClass):
        diff = np.subtract(self.targetVector - computedClass)
        return np.linalg.norm(diff)
        """errors = 0
        for i in range(0,self.targetVector.__len__()):
            if (self.targetVector[i] != computedClass[i]):
                errors = errors + 1
        return errors"""
            
            
            
            
            
            